# -*- coding: utf-8 -*-
import ast
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10092': {
        'API_KEY': 'ccacaa9ee427442da916ff7d767f42b6',
    },
    'gateway': 'http://www.4jipayapi.com/home/index',
    'query_gateway': 'http://www.4jipayapi.com/api/pay/query',

}


# 支付宝：alipay
def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway():
    return APP_CONF['gateway']


def _get_query_gateway():
    return APP_CONF['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest().upper()
    return sign


def generate_verify_sign(parameter, key):
    s = ''
    for k, v in sorted(parameter.items()):
        s += '%s=%s&' % (k, v)
    s += 'Key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params.pop('Sign')
    calculated_sign = generate_verify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("sijipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


# 去掉小数后最后为零的位
def _money(pay_amount):
    money = str(float(pay_amount))
    if money.endswith('0'):
        return money[:money.index('0', -1) - 1]
    return money


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('ReqTimestamp', '%.f' % time.time()),  # 请求时间戳
        ('MerchantNumber', app_id),  # 商户号
        ('OrderNo', str(pay.id)),  # 订单号
        ('Money', _money(pay_amount)),  # 金额
        ('PayCode', service),  # 通道码
        ('NotifyUrl', '{}/pay/api/{}/sijipay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('ReturnUrl', '{}/pay/api/{}/sijipay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
    ))
    parameter_dict['Sign'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info("sijipay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['OrderNo'])
    html_text = _build_form(parameter_dict, _get_gateway())
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info('sijipay url: %s', url)
    return {'charge_info': url}


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("sijipay notify body: %s", request.body)
    # data = eval(request.body)
    data = ast.literal_eval(request.body)
    _LOGGER.info("sijipay notify data: %s, order_id is: %s", data, data['OrderNo'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['OrderNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("sijipay fatal error, pay object not exists, data: %s" % data)
        raise ParamError('sijipay event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('sijipay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('sijipay pay %s has been processed' % pay_id)
    mch_id = pay.mch_id
    trade_status = str(data['OrderState'])
    trade_no = str(pay_id)
    total_fee = float(data['RealMoney'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '2':
        _LOGGER.info('sijipay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    pay = get_pay(pay_id)
    parameter_dict = OrderedDict((
        ('MerchantNumber', app_id),  # 商户号
        ('OrderNo', str(pay.id)),  # 订单号
        ('ReqTimestamp', '%.f' % time.time()),  # 请求时间戳
    ))
    parameter_dict['Sign'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info('sijipay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['OrderNo'])
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_query_gateway(), data=json.dumps(parameter_dict), headers=headers, timeout=5)
    data = json.loads(response.text)
    # verify_notify_sign(data, api_key)
    _LOGGER.info('sijipay query response: %s', data)
    if response.status_code == 200:
        data = data['Data']
        trade_status = str(data['OrderState'])
        total_fee = float(data['RealMoney'])
        trade_no = str(data['OrderNo'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        if trade_status == '2':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('sijipay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
        else:
            _LOGGER.info(
                'sijipay query order success,but not pay success, trade_status:%s ' % trade_status)
    else:
        _LOGGER.warn('sijipay query error, status_code: %s', response.status_code)
